<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品促销ajax类
 * @package  	ajax
 * @subpackage  backend
 * @author   	allen.qiang
 */
quanli_require('module/base/promotion/promotionGoods.class.php');
class ajax_promotionGoods {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //查询商品促销
                    $this->searchPromotionGoods();
                    break;
                case 6: //得到赠品商品信息
                    $this->getGoodsInfo();
                    break;

                case 7: //查询支付方式的付款方式
                    $this->getPayTypePayment();
                    break;

                case 100:

                    if (!isset($_REQUEST['act']) || !in_array($_REQUEST['act'], array('del', 'edit', 'change'))) {
                        returnJsonData('参数错误');
                    }
                    if ($_REQUEST['act'] == 'edit') {

                        $this->savePromotionGoods();//新增、修改商品促销

                    } else if ($_REQUEST['act'] == 'del') {

                        $this->deletePromotionGoods();//删除商品促销

                    } else if ($_REQUEST['act'] == 'change') {

                        $this->promotionGoodsStatus();//启用、禁用商品促销

                    }

                    break;
                case 200: //商品促销配置保存 add by allen.qiang 2015-05-03
                    $this->promotionGoodsConfigSave();
                    break;
                default:
                    returnJsonData('参数错误');
                    break;
            }

        }else {

            returnJsonData('参数错误');

        }

    }

    /**
     * 得到商品的信息
     *
     */
    private function getGoodsInfo (){
        global $G_PGLOB;
        //参数检查
        if(!isset($_REQUEST['sku']) || $_REQUEST['sku'] == '' ){
            echo json_encode(array('code' => 400 , 'message' => '商品参数错误'));
            die() ;
        }

        //得到商品信息
        $sku = $_REQUEST['sku'] ;
        $goodsInfo = new entity('goods_sale') ;
        $goodsInfo->product_code = $sku ;
        if(!$G_PGLOB->DBCA->fetch($goodsInfo)){
            echo json_encode(array('code' => 400 , 'message' => sprintf('sku「%s」的商品不存在' , $sku)));
            die() ;
        }

        //判断商品是否已经下架
        if($goodsInfo->useFlg == 0 || $goodsInfo->forsale == 0){
            echo json_encode(array('code' => 400 , 'message' => sprintf('sku「%s」的商品已经下架' , $sku)));
            die() ;
        }

        //商品信息数组
        $result_array = array(
            'code' 	  => 200,
            'message' => 'OK',
            'data' 	  => array(
                'sku'   	=> $goodsInfo->product_code,
                'postID'   	=> $goodsInfo->postID,
                'goodsName' => $goodsInfo->goodsName,
                'salePrice' => $goodsInfo->salePrice,
                'spec' 		=> $goodsInfo->spec)
        );

        echo json_encode( $result_array );
    }
    /**
     * 查询商品促销
     */
    private function searchPromotionGoods() {

        global $G_PGLOB;

        //查询条件
        $promotionGoods = new promotionGoods( $G_PGLOB->DBCA ) ;
        $result_data = $promotionGoods->promotionGoodsList( $_REQUEST ) ;

        //查询结果
        $result_array = array(
            'page'  => $_REQUEST['page'] ,
            'total' => $_REQUEST['count'] ,
            'rows'  => array()
        );

        if ($result_data) {
            $edit_permission = $G_PGLOB->has_permission(4504);
            foreach($result_data as &$p_g) {
                $bargainType = '' ;
                if($p_g->type == 1)
                    $bargainType = '立减 ' ;
                else if($p_g->type == 2)
                    $bargainType = '特价 ' ;
                else if($p_g->type == 3)
                    $bargainType = '免运费 ' ;
                else if($p_g->type == 4)
                    $bargainType = '送积分 ' ;
                else if($p_g->type == 6)
                    $bargainType = '折扣' ;

                if ($edit_permission) {
                    $result_array['rows'][] = array(
                        'id' 	=> $p_g->promotionID,
                        'cell' 	=> array(
                            '<a href="javascript: void(0);" onclick="promotion.edit(' . $p_g->promotionID . ')">修改</a>&nbsp;<a href="javascript: void(0);" onclick="promotion.config(' . $p_g->promotionID . ')">配置</a>&nbsp;' ,
                            $p_g->promotionID ,
                            $p_g->title,
                            $p_g->priority	,
                            $bargainType,
                            $p_g->startDate	,
                            $p_g->endDate	,
                            $p_g->useFlg == 1 ?
                                '<a href="javascript: void(0);" onclick="promotion.doAction(' . $p_g->promotionID . ', 0) " >启用</a>' :
                                '<a href="javascript: void(0);" onclick="promotion.doAction(' . $p_g->promotionID . ', 1 ) " >禁用</a>' ,
                        ),
                    );
                }else{
                    $result_array['rows'][] = array(
                        'id' 	=> $p_g->promotionID,
                        'cell' 	=> array(
                            $p_g->promotionID ,
                            $p_g->title,
                            $p_g->priority	,
                            $bargainType,
                            $p_g->startDate	,
                            $p_g->endDate
                        ),
                    );
                }
            }
        }

        echo json_encode( $result_array );
    }

    /**
     * 保存商品促销信息
     *
     */
    private function savePromotionGoods () {
        global $G_PGLOB;

        //把得到的城市，支付方式，促销渠道，会员等级数组从新组装成类似（1,2,3）的字符串
        $city_str = isset($_REQUEST['cityID']) ? implode(",",$_REQUEST['cityID']) : ""; //存储城市ID的字符串
        $rank_str = isset($_REQUEST['rankID']) ? implode(",",$_REQUEST['rankID']) : ""; //存储会员等级ID的字符串
        $payType_str = isset($_REQUEST['payTypeID']) ? implode(",",$_REQUEST['payTypeID']) : "";  //存储支付方式ID的字符串
        $payment_array = isset($_REQUEST['paymentID']) ? $_REQUEST['paymentID'] : array();  //存储付款方式ID的字符串
        $promotion_channel_str = isset($_REQUEST['promotionChannelID']) ? implode(",",$_REQUEST['promotionChannelID']) : ""; //存储促销渠道ID的字符串
        $_REQUEST['cityID'] = $city_str;
        $_REQUEST['rankID'] = $rank_str;
        $_REQUEST['payTypeID'] = $payType_str;
        $_REQUEST['paymentID'] = $payment_array;
        $_REQUEST['promotionChannelID'] = $promotion_channel_str;
        $_REQUEST['creator'] = $G_PGLOB->currentUserID;
        $promotionGoods 	 = new promotionGoods( $G_PGLOB->DBCA ) ;
        $result_array 		 = $promotionGoods->savePromotionGoodsInfo( $_REQUEST );
        echo json_encode($result_array);
    }


    /**
     * 删除商品促销信息
     *
     */
    private function deletePromotionGoods () {
        global $G_PGLOB;

        $promotionGoods = new promotionGoods( $G_PGLOB->DBCA ) ;
        $result_array 	  = $promotionGoods->deletePromotionGoods( $_REQUEST ) ;
        echo json_encode($result_array);
    }

    /**
     * 更新商品促销使用状态
     *
     */
    private function promotionGoodsStatus () {
        global $G_PGLOB;

        $promotionGoods = new promotionGoods( $G_PGLOB->DBCA ) ;
        $result_array 	  = $promotionGoods->promotionGoodsStatus( $_REQUEST ) ;
        echo json_encode($result_array);
    }

    /**
     * 查询支付方式下的付款方式
     */
    private function getPayTypePayment(){

        if(!isset($_REQUEST['payTypeID']) || empty($_REQUEST['payTypeID'])){
            $_REQUEST['payTypeID'] = 0;
        }

        quanli_require('module/base/system/sysPayment.class.php');

        $sysPayment = new sysPayment();

        $payTypeID_array = $_REQUEST['payTypeID'];

        $paymentID_array = array();

        if(isset($_REQUEST['paymentID']) && !empty($_REQUEST['paymentID'])){
            foreach($_REQUEST['paymentID'] as &$payment){

                $result = explode('-',$payment);
                $paymentID_array[] = $result[1];
            }
        }

        $return_array = array();

        if($payTypeID_array){
            foreach($payTypeID_array as &$payTypeID){

                $arg_array = array(
                    'payTypeID' => $payTypeID
                );

                $payment_array = $sysPayment->searchPaymentMethod( $arg_array );

                if(!$payment_array){
                    continue;
                }

                foreach($payment_array as &$payment){

                    $select = 0;

                    if(in_array($payment['id'], $paymentID_array)){
                        $select = 1;
                    }

                    $return_array[] = array(
                        'payTypeID' => $payment['payTypeID'],
                        'paymentID' => $payment['id'],
                        'name' => $payment['name'],
                        'select' => $select
                    );

                }

            }
        }

        if(empty($return_array)){
            $return_array = null;
        }

        returnJsonData('ok', 200, $return_array);

    }

    /**
     * 商品促销配置保存
     * add by allen.qiang 2015-05-03
     */
    private function promotionGoodsConfigSave(){
        global $G_PGLOB;

        $config_code = $_POST['config_code'];

        $_POST['paymentID'] = isset($_POST['paymentID']) ? $_POST['paymentID'] : '';



        //保存、新增信息
        foreach($_POST as $config_key => $config_value){

            //排除config_code
            if($config_key == 'config_code')
                continue;

            $activityConfig = new entity('activity_config');
            $activityConfig->creator = 'system';
            $activityConfig->config_code = $config_code;
            $activityConfig->config_key = $config_key;

            if(is_array($config_value)){
                $activityConfig->config_value = implode(',',$config_value);
            }else{
                $activityConfig->config_value = $config_value;
            }

            //先查询有无记录
            $result = $G_PGLOB->DBCA->stmt_query("select uuid,config_value from activity_config where config_code='{$config_code}' and config_key='{$config_key}'");

            if($result){
                $activityConfig->uuid = $result[0]->uuid;

                //值相等不更新
                if($config_value == $result[0]->config_value)
                    continue;
            }else{

                //值为空不新增或者更新
                if($config_value == '')
                    continue;
            }

            $G_PGLOB->DBCA->save($activityConfig);
        }
        echo json_encode(array( 'code' => 200, 'message' => '保存成功' ));
    }
}